import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { throwHttpException1 } from '@/utils/nesjUtils';

// 校验入参
@Injectable()
class CheckParamIsEmptyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // 1、校验整体参数是否传递

    if (Object.keys(req.body).length == 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！',
        data: '',
      });
    }
    const requiredFields = [
      { name: '手机号', field: 'Phone' },
      { name: '短信类型', field: 'SmsTypeCode' },
    ];
    const bodyKeys = Object.keys(req.body);
    const errFields = requiredFields.filter((f) => {
      if (!bodyKeys.includes(f.field)) {
        return f;
      }
    });

    if (errFields.length != 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！必填项: ${errFields.map((f) => f.name).join('、')}`,
        data: '',
      });
    }
    if (requiredFields.filter((f) => !req.body[f.field]).length != 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！必填项: ${requiredFields
          .filter((f) => !req.body[f.field])
          .map((f) => f.name)
          .join('、')}`,
        data: '',
      });
    }
    next();
  }
}

export default {
  CheckParamIsEmptyMiddleware,
};
